package com.youlu.campus.service.visitor.impl;

import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.entity.UserOtherInfo;
import com.youlu.campus.service.visitor.UserOtherInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;


@Slf4j
@Service
public class UserOtherInfoServiceImpl implements UserOtherInfoService {
    @Autowired
    private MongoTemplate monogoTemplate;

    @Override
    public UserOtherInfo findByUserId(String userId) {
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId));
        return monogoTemplate.findOne(query, UserOtherInfo.class);
    }

    @Override
    public boolean update(UserOtherInfo userOtherInfo) {
        Query query = new Query().addCriteria(Criteria.where("userId").is(userOtherInfo.getUserId()));
        boolean up = false;
        Update update = new Update();
        if (StringUtils.isNotBlank(userOtherInfo.getNickName())) {
            update.set("nickName", userOtherInfo.getNickName());
            up = true;
        }
        if (StringUtils.isNotBlank(userOtherInfo.getAvatarUrl())) {
            update.set("avatarUrl", userOtherInfo.getAvatarUrl());
            up = true;
        }
        if (up) {
            update.set("updatedTime", new Date());
            UpdateResult updateResult = monogoTemplate.updateFirst(query, update, UserOtherInfo.class);
            return updateResult.getModifiedCount() > 0 ? true : false;
        }
        return false;
    }

    @Override
    public boolean create(UserOtherInfo userOtherInfo) {
        if (StringUtils.isNotBlank(userOtherInfo.getId())) {
            userOtherInfo.setId(null);
        }
        if (Objects.nonNull(userOtherInfo.getCreatedTime())) {

        }

        userOtherInfo.setCreatedTime(new Date());
        try {
            monogoTemplate.insert(userOtherInfo);
            return true;
        } catch (Exception e) {
            log.error(":>>> 新增用户其他信息错误:{}", e);
            return false;
        }
    }
}
